<!--  固定表 -->
<template>
  <div>
    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>编码目录</label>
          <!-- <span @click="showFolder()"
						><i class="el-icon el-icon-s-tools"></i
					></span> -->
        </div>
        <div class="flex-tree">
          <div
            :class="tableIndex == item.Id ? 'hover tree-item' : 'tree-item'"
            v-for="item in tableList"
            v-bind:key="item.Id"
            @click="tabClick(item)"
          >
            {{ item.Name }}
          </div>
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar>
          <div class="searchContent">
            <el-input
              v-model="fName"
              placeholder="请输入目录名称"
              size="mini"
              clearable
              style="width: 150px; margin-right: 10px"
              @keyup.enter.native="handleEnter"
            ></el-input>
            <custom-button
              type="search"
              style="margin-right: 10px"
              @searchClick="searchClick"
            ></custom-button>
            <custom-button
              type="add"
              title="新增父级"
              style="margin-right: 10px"
              @addClick="showFolder"
            ></custom-button>

            <custom-button
              type="add"
              title="新增子级"
              style="margin-right: 10px"
              @addClick="addChild"
            ></custom-button>

            <el-button
              size="mini"
              style="background-color: #67c23a; color: #fff; border: none"
              @click="editItem"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>

            <el-button
              v-if="folderType == 1"
              size="mini"
              style="
                margin-right: 10px;
                background-color: #fc6a6e;
                color: #fff;
                border: none;
              "
              @click="deleteOne"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button
              v-if="folderType != 1"
              size="mini"
              style="
                margin-right: 10px;
                background-color: #fc6a6e;
                color: #fff;
                border: none;
              "
              @click="deleteAll"
            >
              <i class="el-icon-delete"></i> 批量删除
            </el-button>
            <!-- <custom-button
							v-if="folderType != 1"
							type="custom"
							title="导入"
							@customClick="addClick"
							icon="el-icon-upload2"
						></custom-button> -->

            <custom-button
              type="custom"
              title="导入"
              @customClick="addClick"
              icon="el-icon-upload2"
            ></custom-button>
          </div>
        </navigation-bar>
        <div class="tablePadding" v-if="tableData && tableData.length > 0">
          <codeSpread
            :dataSource="tableData"
            @cellClick="cellClick"
            :key="keyValue"
            ref="spread"
          ></codeSpread>
          <!-- <el-table
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="Id"
            border
            default-expand-all
            size="medium"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column prop="FolderName" label="目录名称" width="180">
            </el-table-column>
            <el-table-column prop="EnCode" label="编码" width="180">
            </el-table-column>
            <el-table-column prop="FolderTypeName" label="目录类型">
            </el-table-column>

            <el-table-column fixed="right" label="操作" :width="120">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="addRow(scope.row)"
                  type="text"
                  size="small"
                >
                  新增
                </el-button>

                <el-button
                  @click.native.prevent="editRow(scope.row)"
                  type="text"
                  size="small"
                >
                  编辑
                </el-button>

                <el-button
                  @click.native.prevent="deleteRow(scope.row)"
                  type="text"
                  size="small"
                  style="color: red"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table> -->
        </div>
        <div class="tablePadding noData" v-else>暂无数据</div>
      </div>
    </div>
    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <div>
          <resourceAdd @getData="getData"></resourceAdd>
        </div>
      </custom-dialog>
    </div>

    <div v-if="dialogFolderShow">
      <custom-dialog
        :title="dialogFolderTitle"
        size="large"
        @dialogClose="dialogFolderClose"
      >
        <form-index
          :formConfig="formConfigFolder"
          @submit="folderSubmit"
          :type="typeFolder"
          @formInputChange="formInputFolderChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="showloading">
      <loadingMask></loadingMask>
    </div>

    <div v-if="showPwdJudge">
      <pwdJudge @close="showPwdJudge = false" @success="startDown"></pwdJudge>
    </div>
  </div>
</template>

<script>
import { presetFieldsForm } from "@/assets/form/managementCenter/expandManage/presetFieldsForm";
import { zkForm } from "@/assets/form/managementCenter/zkForm";
import customDialog from "@/components/customComponents/customDialog";
import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
// import singleTable from "@/components/customComponents/customeTable/singleTable.vue"
// import tableIndex from "@/components/customComponents/customeTable/tableHeightIndex"
import loadingMask from "@/components/customComponents/loading";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
import { Utility } from "@/libs/utility";
import codeSpread from "./codeSpread.vue";
import resourceAdd from "./resourceAdd.vue";
import pwdJudge from "@/components/customComponents/pwdJudge";
export default {
  components: {
    navigationBar,
    customButton,
    // tableIndex,
    customDialog,
    // singleTable,
    formIndex,
    resourceAdd,
    codeSpread,
    loadingMask,
    pwdJudge,
  },
  data() {
    return {
      showPwdJudge: false,
      currentSelectDown: {}, // 存储当前点击的那行数据
      lastName: "",
      fName: "",
      keyValue: parseInt(Math.random() * 10000),
      cellItem: {
        tempData: [],
        tempCols: [],
        tempRows: [],
      },
      showloading: true,
      tableData: [],
      curHeight: 100,
      folderData: null,
      fatherFolderId: "0",
      dialogFolderTitle: "新增分类",
      formConfigFolder: zkForm,
      typeFolder: "add",
      dialogFolderShow: false,
      data: [],
      tableIndex: "635747017666630",
      folderType: 1,
      selectItem: [],
      username: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "FileName",
          label: "文件名称",
        },
        {
          prop: "FileSize",
          label: "文件大小",
        },
        {
          prop: "UploadUser",
          label: "创建人",
        },
        {
          prop: "UploadTime",
          label: "创建时间",
        },
      ],
      btnList: ["delete", "lookViewRow", "downloadRow"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: presetFieldsForm,
      type: "add",
      tableList: [
        {
          Id: "635747017666630",
          Name: "编码附录A",
          type: 1,
        },
        {
          Id: "635947755249733",
          Name: "表12",
          type: 2,
        },
        {
          Id: "635947782459462",
          Name: "表14",
          type: 3,
        },
      ],
    };
  },
  methods: {
    handleEnter() {
      this.searchClick();
    },
    cellClick(e) {
      this.cellItem = {
        tempCols: e.tempCols,
        tempRows: e.tempRows,
        tempData: e.tempData,
      };
    },
    addChild() {
      if (this.cellItem.tempData.length != 1) {
        PopupCommon.notify("info", "请点击一个单元格选中行");
        return;
      }
      this.addRow(this.cellItem.tempData[0]);
    },
    editItem() {
      if (this.cellItem.tempData.length != 1) {
        PopupCommon.notify("info", "请点击一个单元格选中行");
        return;
      }
      this.editRow(this.cellItem.tempData[0]);
    },
    getHeight() {
      this.curHeight = window.innerHeight - 146;
    },
    getData(e) {
      console.log(e, this.tableIndex, this.folderType, "e....");
      var url = `/api/familyfolder/batchAddFolder?folderID=${this.tableIndex}&folderType=${this.folderType}&sheetName=${e.form.sheetName}&rowStartIndex=${e.form.rowStartIndex}&codeColumn=${e.form.codeColumn}&nameColumn=${e.form.nameColumn}`;
      var params = {
        file: e.SingeFile,
      };
      let self = this;
      PopupCommon.notify("info", "导入中，请稍等...");
      self.showloading = true;
      AjaxCommon(url, "postForm", params).then((res) => {
        if (res.data.status == 200) {
          self.showloading = false;
          PopupCommon.notify("success", "导入成功");
          self.initPage();
          self.dialogShow = false;
        } else {
          self.showloading = false;
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    tabClick(data) {
      if (this.tableIndex == data.Id) {
        return;
      }
      this.showloading = true;
      this.tableIndex = data.Id;
      this.folderType = data.type;
      this.initPage();
    },
    dialogFolderClose() {
      this.dialogFolderShow = false;
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    folderSubmit(d) {
      let self = this;
      var p = `?IsDelete=false&FolderID=${this.tableIndex}&FolderName=${d.FolderName}&LastFolderId=${self.fatherFolderId}&FolderType=${this.folderType}&EnCode=${d.EnCode}`;
      var titleOpr = "新增成功";
      if (d.Id) {
        p += `&Id=${d.Id}`;
        titleOpr = "编辑成功";
      }
      AjaxCommon(`/api/familyfolder${p}`, "post", {})
        .then((res) => {
          console.log(res, "res..................");
          if (res.data.status == 200) {
            PopupCommon.notify("success", titleOpr);
            if (titleOpr == "新增成功") {
              self.initPage(self.cellItem.tempRows);
            } else {
              console.log(d, self.cellItem, "value.....");
              self.$refs.spread.setValue(
                self.cellItem.tempRows,
                0,
                d.FolderName
              );
              self.$refs.spread.setValue(self.cellItem.tempRows, 1, d.EnCode);
            }
            self.dialogFolderClose();
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    showFolder() {
      let formConfigItem = this.formConfigFolder;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfigFolder = formConfigItem;
      this.fatherFolderId = "0";
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增编码";
      this.dialogFolderShow = true;
    },
    editRow(data) {
      this.type = "edit";
      let formConfigItem = this.formConfigFolder;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = data[t[res]];
          }
        });
      });
      this.formConfigFolder = formConfigItem;
      this.fatherFolderId = data.FatherFolderId;
      this.typeFolder = "edit";
      this.dialogFolderTitle = "编辑编码";
      this.dialogFolderShow = true;
    },
    addRow(data) {
      this.type = "add";
      let formConfigItem = this.formConfigFolder;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfigFolder = formConfigItem;
      this.fatherFolderId = data.Id;
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增子编码";
      this.dialogFolderShow = true;
    },

    deleteFolder(item) {
      let self = this;
      const id = item.Id;
      console.log(item, "item");
      PopupCommon.confirm(`确定删除【${item.FolderName}】？`)
        .then(() => {
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder();
              self.dialogFolderClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    singleBtnClick() {
      if (this.yzzdSelect.length == 0) {
        PopupCommon.notify("info", "请选择预置资源");
        return;
      }
      this.dialogShow = false;
      console.log(this.yzzdSelect, "this.yzzdSelect......");
    },
    singleHandleSelectionChange(e) {
      this.yzzdSelect = e;
    },
    deleteOne() {
      // 编码附录A删除只能删除单个子级
      if (this.cellItem.tempData.length != 1) {
        PopupCommon.notify("info", "请先用鼠标左键点击一行最低层子级进行选择");
        return;
      }
      console.log(this.cellItem.tempData[0], "item.....");
      var id = this.cellItem.tempData[0].Id;
      var name = this.cellItem.tempData[0].FolderName;
      let self = this;
      PopupCommon.confirm(`确定删除${name}？`)
        .then(() => {
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", null).then(
            (res) => {
              if (res.data.status == 200) {
                PopupCommon.notify("success", "删除成功");
                self.initPage();
              } else {
                PopupCommon.notify("error", res.data.msg);
              }
            }
          );
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消删除");
        });
    },
    deleteAll() {
      // 编码附录A删除只能删除子级
      // v-if="folderType != 1"
      if (this.cellItem.tempData.length == 0) {
        PopupCommon.notify("info", "请先用鼠标左键拖动行进行多选");
        return;
      }
      var childrenList = this.cellItem.tempData.filter(
        (t) => typeof t.children == "undefined"
      );
      var parentCount = this.cellItem.tempData.length - childrenList.length;

      var msg = "";
      if (parentCount > 0) {
        msg = `已自动过滤掉${parentCount}条父级数据，是否删除${childrenList.length}条子级数据？`;
      } else {
        msg = `是否删除${childrenList.length}条子级数据？`;
      }
      if (childrenList.length == 0) {
        PopupCommon.notify("info", "没有能删除的子级数据");
        return;
      }
      let self = this;
      PopupCommon.confirm(msg)
        .then(() => {
          const id = childrenList.map((t) => t.Id);
          AjaxCommon("/api/familyfolder/batchDelete", "deleteForm", id).then(
            (res) => {
              if (res.data.status == 200) {
                PopupCommon.notify("success", "删除成功");
                self.initPage();
              } else {
                PopupCommon.notify("error", res.data.msg);
              }
            }
          );
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消删除");
        });
    },
    handleSelectionChange(d) {
      this.selectItem = d;
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    submit(d) {
      console.log(d);
      // let self = this
      // console.log(d)
      // if (d.id) {
      // 	AjaxCommon("/ccdc/cfg/device/device/edit", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 				this.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // } else {
      // 	delete d.id
      // 	AjaxCommon("/ccdc/cfg/device/device/add", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      if (this.fName) {
        var isSame = true;
        if (this.lastName != this.fName) {
          this.lastName = this.fName;
          isSame = false;
        }
        this.$refs.spread.search(this.fName, isSame);
      } else {
        PopupCommon.notify("info", "请输入目录名称");
      }
    },
    resetClick() {
      this.username = "";
    },
    addClick() {
      // // 测试
      // AjaxCommon("/api/familyresouce/downloadfile/1", "get", null)

      if (this.tableIndex == "") {
        PopupCommon.notify("info", "请先选择左侧的资源分类");
        return;
      }
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle = "导入编码文件选择";
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    startDown() {
      this.showPwdJudge = false;
      const item = this.currentSelectDown;
      const id = item.Id;
      // let self = this
      AjaxCommon("/api/ResourceFile/downloadfile/" + id, "getBlob", null).then(
        (res) => {
          if (res?.status == 200) {
            // var data = self.stringToArrayBuffer(res.data)
            var blob = new Blob([res.data]);
            const href = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.download = item.FileName;
            link.href = href;
            link.click();
            try {
              document.body.removeChild(link);
            } catch (error) {
              console.log(error.message);
            }
            URL.revokeObjectURL(href); // 释放内存
          } else {
            PopupCommon.notify("error", res?.data?.msg ?? "资源未找到");
          }
        }
      );
    },
    downloadRow(d) {
      this.currentSelectDown = d.data;
      this.showPwdJudge = true;
    },
    stringToArrayBuffer(str) {
      console.log(str, "str....................");
      var buf = new ArrayBuffer(str.length);
      var bufView = new Uint8Array(buf);
      for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    },
    deleteRow(d) {
      let self = this;
      PopupCommon.confirm("此操作将删除该数据, 是否继续?")
        .then(() => {
          const id = d.Id;
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", {
            optReason: d.optReason,
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initPage();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消删除");
        });
    },
    // 初始化事件
    initPage(row) {
      let self = this;
      var id = this.folderType;
      this.showloading = true;
      AjaxCommon(
        "/api/familyfolder/GetFullFolder?FolderType=" + id,
        "get"
      ).then((res) => {
        if (res.data.status == 200) {
          let treeDataList = [];
          Utility.createTreeTableData(res.data.response, treeDataList);
          console.log(treeDataList, "treeDataList................");
          sessionStorage.setItem("globalData", JSON.stringify(treeDataList));
          self.tableData = treeDataList;
          self.keyValue = parseInt(Math.random() * 10000);
          self.showloading = false;

          if (row) {
            setTimeout(() => {
              self.$refs.spread.goToPosition(row, 0);
            }, 1000);
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
      this.initPage();
    });

    /*窗口自适应，关键代码*/
    window.onresize = () => {
      this.getHeight();
    };
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: calc(100vh - 168px);
  overflow-y: auto;
  padding: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree-btn {
  color: red;
}
.tablePadding {
  margin: 10px 0;
  background-color: #fff;
  height: calc(100vh - 147px);
}

.noData {
  padding-top: 100px;
  text-align: center;
  color: #999;
}
</style>
